package br.com.projetosivan.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ImagemProdutoSvlt
 */
public class ImagemProdutoSvlt extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImagemProdutoSvlt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext sc = getServletContext();
		
		String filename = "c:/app/images/produtos/"+ request.getParameter("filename");
		// Get the MIME type of the image
		String mimeType = sc.getMimeType(filename);
		if (mimeType == null) {
			sc.log("Could not get MIME type of "+filename);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		// Set content type
		response.setContentType(mimeType);
		// Set content size
		File file = new File(filename);
		response.setContentLength((int)file.length());
		// Open the file and output streams
		FileInputStream in = new FileInputStream(file);
		if(file.exists()){  
            InputStream is = new FileInputStream(file);   
            byte[] arquivo = new byte[is.available()];     
            is.read(arquivo);     
            is.close(); 
            OutputStream out = response.getOutputStream();
    		response.setContentLength(arquivo.length);
    		
    		out.write(arquivo, 0, arquivo.length);	
    		out.flush();
    		out.close();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
